package com.wlyuan.open.scanner.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wlyuan.open.scanner.dao.entity.ShareCompanyDO;
import com.wlyuan.open.scanner.dao.mapper.CompanyMapper;
import com.wlyuan.open.scanner.dao.mapper.ShareCompanyMapper;
import com.wlyuan.open.scanner.dao.mapper.UserThirdMapper;
import com.wlyuan.open.scanner.domain.tenant.InviterInfo;
import com.wlyuan.open.scanner.domain.tenant.TenantConvert;
import com.wlyuan.open.scanner.domain.user.UserConvert;
import com.wlyuan.open.scanner.repository.ShareCompanyRepository;
import com.wlyuan.open.scanner.repository.UserRepository;
import com.wlyuan.open.scanner.utils.enums.tenant.ShareCompanyTypeEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @author lijing
 * @description
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ShareCompanyRepositoryImpl implements ShareCompanyRepository {
    private final CompanyMapper companyMapper;
    private final ShareCompanyMapper shareCompanyMapper;
    private final UserThirdMapper userThirdMapper;
    private final UserRepository userRepository;

    @Override
    public List<InviterInfo> getInviter() {
        //根据被邀请者查询信息
        logger.info("邀请人sharecompanySharer is not null and 邀请类型 sharecompanySharetype is not null");
        var shareCompany = getShare();
        logger.info("老数据数据量，size：{}", shareCompany.size());
        if (CollectionUtils.isEmpty(shareCompany)) {
            return Collections.emptyList();
        }
        var list = getCompanyInviter(shareCompany);
        logger.info("找到邀请者的数据，size：{}", list.size());
        return list;
    }

    @Override
    public InviterInfo getInviterByCompanyId(Long companyId) {
        QueryWrapper<ShareCompanyDO> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ShareCompanyDO::getSharecompanyCompanyid, companyId);
        var shareCompany = shareCompanyMapper.selectOne(wrapper);
        if (!Optional.ofNullable(shareCompany).isPresent()) {
            return null;
        }
        var list = getCompanyInviter(Arrays.asList(shareCompany));
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.stream().findFirst().orElse(null);
    }

    /**
     * 获取所有邀请记录
     *
     * @return
     */
    private List<ShareCompanyDO> getShare() {
        //获取所有的邀请记录
        QueryWrapper<ShareCompanyDO> wrapper = new QueryWrapper<>();
        wrapper.lambda().isNotNull(ShareCompanyDO::getSharecompanySharer).isNotNull(ShareCompanyDO::getSharecompanySharetype);
        return shareCompanyMapper.selectList(wrapper);
    }

    /**
     * 获取企业邀请信息
     *
     * @param list
     * @return
     */
    private List<InviterInfo> getCompanyInviter(List<ShareCompanyDO> list) {
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        List<InviterInfo> result = new ArrayList<>();
        list.stream().forEach(shareCompany -> {
            //邀请类型
            var shareType = shareCompany.getSharecompanySharetype();
            //被邀请者 （租户）
            var companyId = shareCompany.getSharecompanyCompanyid();
            //邀请者
            var shareId = shareCompany.getSharecompanySharer().longValue();
            //企业邀请者
            if (ShareCompanyTypeEnum.isCompany(shareType)) {
                var companyInviter = getCompanyInviter(companyId, shareId);
                Optional.ofNullable(companyInviter).ifPresent(c -> result.add(c));
            }
            //个人邀请者
            if (ShareCompanyTypeEnum.isPersonal(shareType)) {
                var companyInviter = getPersonalInviter(companyId, shareId);
                Optional.ofNullable(companyInviter).ifPresent(c -> result.add(c));
            }
        });
        return result;
    }

    /**
     * 企业邀请者
     *
     * @param companyId 被邀请者
     * @param shareId   邀请者
     * @return
     */
    private InviterInfo getCompanyInviter(Long companyId, Long shareId) {
        //根据邀请者获取信息
        var company = companyMapper.selectById(shareId);
        return TenantConvert.convertInviter(company, companyId);
    }

    /**
     * 个人邀请者
     *
     * @param companyId 被邀请者
     * @param shareId   邀请者
     * @return
     */
    private InviterInfo getPersonalInviter(Long companyId, Long shareId) {
        //根据邀请者获取userThird信息
        var userThird = userThirdMapper.selectById(shareId);
        if (ObjectUtils.isEmpty(userThird)) {
            return null;
        }
        //绑定用户
        var bindUserId = userThird.getUserthirdBinduser();
        if (ObjectUtils.isEmpty(bindUserId)) {
            return null;
        }
        //根据绑定用户查询用户
        var user = userRepository.getById(bindUserId);
        return UserConvert.convertInviter(user, companyId);

    }
}
